﻿#include	"Engine.Utils.hpp"
#include	"Engine.String.hpp"

namespace Engine { namespace Utils {
	
	void Params::Parse(int nArgc, char * pArgv[]) {
		_mpCmds.clear();

		if (nArgc > 0) {
			for (int nIdx = 0; nIdx < nArgc; ++nIdx) {
				if (pArgv[nIdx] && pArgv[nIdx][0]) {
					std::string szParam(pArgv[nIdx]);
					int nPos = szParam.find_first_of("=");
					int nLen = szParam.length();
					if (nPos == std::string::npos)
						_mpCmds[szParam] = "";
					else if (nPos == 0)
						continue;
					else if (nPos == nLen - 1)
						_mpCmds[szParam.substr(0, nLen - 1)] = "";
					else
						_mpCmds[szParam.substr(0, nPos)] = szParam.substr(nPos + 1, nLen - 1 - nPos);
				}
			}
		}
	}

	void Params::Parse(const char * szCmd) {
		std::vector<std::string> vCmds = Engine::String::Split(szCmd, " \t\b\r\n");
		_mpCmds.clear();

		for (auto itor = vCmds.begin(); itor != vCmds.end(); ++itor) {
			std::string szParam(*itor);
			int nPos = szParam.find_first_of("=");
			int nLen = szParam.length();
			if (nPos == std::string::npos)
				_mpCmds[szParam] = "";
			else if (nPos == 0)
				continue;
			else if (nPos == nLen - 1)
				_mpCmds[szParam.substr(0, nLen - 1)] = "";
			else
				_mpCmds[szParam.substr(0, nPos)] = szParam.substr(nPos + 1, nLen - 1 - nPos);
		}
	}

	bool Params::Has(const char * szCmd) {
		return _mpCmds.find(szCmd) != _mpCmds.end();
	}

	std::string Params::Get(const char * szCmd) {
		auto itor = _mpCmds.find(szCmd);
		if (itor == _mpCmds.end()) return "";
		return itor->second;
	}

	void Params::Alias(const char * szAlias, const char * szOrg) {
		auto itor = _mpCmds.find(szOrg);
		if (itor != _mpCmds.end()) {
			_mpCmds.insert(std::pair<std::string, std::string>(szAlias, itor->second));
			_mpCmds.erase(szOrg);
		}
	}

}}

